package com.gm.baseplatform.core.tree;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

public class TreeHelper {
	
	public static String buildTreeRootJsonText(String rootName,List<?> treeImpls) {
		List<TreeNode> tree = new ArrayList<TreeNode>();
		TreeNode rootNode = new TreeNode();
		rootNode.setId("0");
		rootNode.setText(rootName);
		rootNode.setChecked(false);
		rootNode.setState(TreeNode.NODE_STATE_OPEN);
		rootNode.setChildren(transferToTreeNode(treeImpls));
		tree.add(rootNode);
		return JSONArray.fromObject(tree).toString();
	}
	
	public static String buildTreeJsonText(List<?> treeImpls) {
		List<TreeNode> treeNodes = transferToTreeNode(treeImpls);
		return JSONArray.fromObject(treeNodes).toString();
	}
	
	public static List<TreeNode> transferToTreeNode(List<?> treeImpls) {
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		for (int i = 0; i < treeImpls.size(); i++) {
			Object treeImpl = treeImpls.get(i);
			if (treeImpl instanceof Treeable) {
				TreeNode treeNode = ((Treeable)treeImpl).buildTreeNode();
				if (treeNode.isHasChildren()) {
					treeNode.setState(TreeNode.NODE_STATE_CLOSE);
				} else {
					treeNode.setState(TreeNode.NODE_STATE_OPEN);
				}
				treeNodes.add(treeNode);
			}
		}
		return treeNodes;
	}
	
}
